package com.stellar.core.encrypt.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @ClassName：DESEncryptHandler
 * @Description: DES加密解密
 * @Author: Jqcc
 * @Date: 2025/3/13
 */
@Slf4j
public class DESEncryptHandler implements EncryptHandler {

    /**
     * 密钥
     */
    public static final String DESKEY = "DESKEY";

    /**
     * 解密
     *
     * @param data
     * @return
     */
    @Override
    public String decrypt(String data) {
        return decrypt(data, DESKEY);
    }

    /**
     * 加密
     *
     * @param data
     * @return
     */
    @Override
    public String encrypt(String data) {
        return encrypt(data, DESKEY);
    }

    /**
     * 加密
     *
     * @param data
     * @param key
     * @return
     */
    public static String encrypt(String data, String key) {
        if (StringUtils.isEmpty(data) || StringUtils.isEmpty(key)) {
            log.info("参数和密钥不允许为空");
            return null;
        }
        String strs = null;
        try {
            byte[] bytes = encryptOrDecrypt(Cipher.ENCRYPT_MODE, data.getBytes(), key.getBytes());
            // base64编码字节
            strs = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            log.error("加密失败，errormsg={}", e.getMessage());
        }
        return strs;
    }

    /**
     * 解密
     *
     * @param data
     * @param key
     * @return
     */
    public static String decrypt(String data, String key) {
        if (StringUtils.isEmpty(data) || StringUtils.isEmpty(key)) {
            log.info("参数和密钥不允许为空");
            return null;
        }
        String strs = null;
        try {
            byte[] src = Base64.getDecoder().decode(data);
            byte[] bytes = encryptOrDecrypt(Cipher.DECRYPT_MODE, src, key.getBytes());
            strs = new String(bytes, "utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error("解密失败，errormsg={}", e.getMessage());
        }
        return strs;
    }

    public static byte[] encryptOrDecrypt(int mode, byte[] data, byte[] key) {
        try {
            // 强随机数生成器 (RNG)
            SecureRandom random = new SecureRandom();
            // DESKeySpec是一个成加密密钥的密钥内容的（透明）规范的接口。
            DESKeySpec desKey = new DESKeySpec(key);
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // 得到密钥对象SecretKey
            SecretKey securekey = keyFactory.generateSecret(desKey);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES");
            // 用密匙初始化Cipher对象
            cipher.init(mode, securekey, random);
            // 现在，获取数据并加密，正式执行加密操作
            return cipher.doFinal(data);
        } catch (Throwable e) {
            log.error("{}", e);
        }
        return null;
    }

    public static void main(String[] args) {
        DESEncryptHandler handler = new DESEncryptHandler();
        System.out.println(handler.encrypt("123456"));
        System.out.println(handler.decrypt(handler.encrypt("123456")));
    }
}

